package com.cyandpos.pad.utils.log;

/**
 * Created by zx on 2018/7/5.
 */

import android.os.Environment;
import android.util.Log;

import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.PubData;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 行为日志记录
 */
public class MessageLog {

    public static ConcurrentLinkedQueue tempQueue=new ConcurrentLinkedQueue<Object>();

    /**
     * 记录行为信息记录到本地
     * @param ai
     */
    public static synchronized void writeLog(String ai){
        tempQueue.add(ai);
        if(!WriteThread.isWriteThreadLive){
            new WriteThread().start();
        }
    }

    /**
     * 打开日志文件并写入日志
     *
     * @return
     * **/
    public static void recordStringLog(String text) {// 新建或打开日志文件
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss:SSS");
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate)+":";
        String strContent=str+text+"\n";

        try {
            File dir = new File(PubData.SD_ROOT_PATH
                    + File.separator + PubData.FILE_ROOT_NAME
                    + File.separator + PubData.FILE_PROJECT_NAME
                    + File.separator + PubData.FILE_CLIENT_NAME
                    + File.separator + f.format(curDate));
            if (!dir.exists())
                dir.mkdirs();
            File file = new File(dir + File.separator+ff.format(curDate)+"_message.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter filerWriter = new FileWriter(file, true);//后面这个参数代表是不是要接上文件中原来的数据，不进行覆盖
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(strContent);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
            Log.d("行为日志写入成功",strContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除日志文件
     */
    public static void deleteLogFile(){
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());//过去一月
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String sLastDate = f.format(m);
        if (!CommonUtils.isSdcardReady()) return;
        int lastInt = Integer.parseInt(sLastDate);
        String sfile = PubData.SD_ROOT_PATH
                + File.separator + PubData.FILE_ROOT_NAME
                + File.separator + PubData.FILE_PROJECT_NAME
                + File.separator + PubData.FILE_CLIENT_NAME;
        File root  = new File(sfile);
        File[] files = root.listFiles();
        if(files ==null || files.length==0){
            root.delete();
            return;
        }
        for(File file:files){
            if(file.isDirectory()){
                String s = file.getName().trim();
                int sInt = Integer.parseInt(s);
                if(sInt<lastInt) {
                    File[] itemArray = file.listFiles();
                    for (File item : itemArray) {
                        if (item.isFile()) {
                            item.delete();
                        }
                    }
                    file.delete();
                }
            }else{
                file.delete();
            }
        }
    }

//    /**
//     * 删除本地异常信息
//     */
//    public static void deleLocalCrashLog(){
//        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
//        Calendar c = Calendar.getInstance();
//        c.setTime(new Date());//过去一月
//        c.add(Calendar.MONTH, -1);
//        Date m = c.getTime();
//        String sLastDate = f.format(m);
//        if (!CommonUtils.isSdcardReady()) return;
//        int lastInt = Integer.parseInt(sLastDate);
//        String sfile = PubData.SD_ROOT_PATH
//                + File.separator + PubData.FILE_ROOT_NAME
//                + File.separator + PubData.FILE_PROJECT_NAME
//                + File.separator + PubData.FILE_CRASH_NAME
//                ;
//        File root  = new File(sfile);
//        File[] files = root.listFiles();
//        if(files ==null || files.length==0){
//            root.delete();
//            return;
//        }
//        for(File file:files){
//            if(file.isDirectory()){
//                String s = file.getName().trim();
//                int sInt = Integer.parseInt(s);
//                if(sInt<lastInt) {
//                    File[] itemArray = file.listFiles();
//                    for (File item : itemArray) {
//                        if (item.isFile()) {
//                            item.delete();
//                        }
//                    }
//                    file.delete();
//                }
//            }else{
//                file.delete();
//            }
//        }
//    }

    public static void deleteTikcets() {
        if (!CommonUtils.isSdcardReady()) {
            return;
        }
        File f = new File( PubData.SD_ROOT_PATH
                + File.separator + PubData.FILE_ROOT_NAME
                + File.separator + PubData.FILE_PROJECT_NAME
                + File.separator + PubData.FILE_TICKET_NAME
        );
        if (!f.exists())
            f.mkdirs();
        List<File> fileList = getFile(f) ;
        Date now = new Date();
        if(fileList!=null && fileList.size()>0){
            for (File file : fileList) {
                Date date = new Date(file.lastModified());
                if (getDistDates(date, now) >= 7) {
                    file.delete();
                }
            }
        }
    }

    public static void deleteImage() {
        if (!CommonUtils.isSdcardReady()) {
            return;
        }
        File f = new File( PubData.SD_ROOT_PATH
                + File.separator + PubData.FILE_ROOT_NAME
                + File.separator + PubData.FILE_PROJECT_NAME
                + File.separator + PubData.FILE_IMAGE_NAME
        );
        if (!f.exists())
            f.mkdirs();
        List<File> fileList = getFile(f) ;
        if(fileList!=null && fileList.size()>0){
            for (File file : fileList) {
                file.delete();
            }
        }
    }

    public static  List<File> getFile(File file) {// 遍历tickets文件下面的文件
        if (!file.exists())
            file.mkdir();
        List<File> files = new ArrayList<File>();
        File[] fileArray = file.listFiles();
        if (fileArray == null)
            return null;
        for (File f : fileArray) {
            if (f.isFile()) {
                files.add(f);
            } else {
                getFile(f);
            }
        }
        return files;
    }

    public static long getDistDates(Date startDate, Date endDate) {
        long totalDate = 0;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        long timestart = calendar.getTimeInMillis();
        calendar.setTime(endDate);
        long timeend = calendar.getTimeInMillis();
        totalDate = Math.abs((timeend - timestart)) / (1000 * 60 * 60 * 24);
        return totalDate;
    }

    //写日志
    public static void writeLog_gq(String err){
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss:SSS");
        SimpleDateFormat f = new SimpleDateFormat ("yyyyMMdd");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate)+":";
        String strContent=str+err+"\n";
        try {
            File dir = new File(Environment
                    .getExternalStorageDirectory().getPath()
                    + File.separator + "CYLog");
            if (!dir.exists())
                dir.mkdir();
            File file = new File(dir + File.separator + f.format(curDate) +"_"+"CY_log.txt" );
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File.");
        }
    }



}
